package com.qyer.lxp.common.framework.extension;

import com.alibaba.dubbo.rpc.protocol.rest.support.LoggingFilter;
import com.qyer.lxp.common.framework.httpclient.HttpClientUtil;
import com.qyer.lxp.common.framework.util.QyerUtils;

import javax.ws.rs.Path;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import java.io.IOException;
import java.lang.annotation.Annotation;

/**
 * Created by jiangping on 16/6/3.
 */
public class ResponseTraceFilter implements ContainerRequestFilter, ContainerResponseFilter {
    /**
     * Filter method called before a request has been dispatched to a resource.
     * <p>
     * <p>
     * Filters in the filter chain are ordered according to their {@code javax.annotation.Priority}
     * class-level annotation value.
     * If a request filter produces a response by calling {@link ContainerRequestContext#abortWith}
     * method, the execution of the (either pre-match or post-match) request filter
     * chain is stopped and the response is passed to the corresponding response
     * filter chain (either pre-match or post-match). For example, a pre-match
     * caching filter may produce a response in this way, which would effectively
     * skip any post-match request filters as well as post-match response filters.
     * Note however that a responses produced in this manner would still be processed
     * by the pre-match response filter chain.
     * </p>
     *
     * @param requestContext request context.
     * @throws IOException if an I/O exception occurs.
     * @see PreMatching
     */
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        System.out.println("555555555555555555");
    }

    /**
     * Filter method called after a response has been provided for a request
     * (either by a {@link ContainerRequestFilter request filter} or by a
     * matched resource method.
     * <p>
     * Filters in the filter chain are ordered according to their {@code javax.annotation.Priority}
     * class-level annotation value.
     * </p>
     *
     * @param requestContext  request context.
     * @param responseContext response context.
     * @throws IOException if an I/O exception occurs.
     */
    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        Annotation[] annotations = responseContext.getEntityAnnotations();
        Path nameSpace= (Path)annotations[1];
        String response = HttpClientUtil.addHeaderTemplete(nameSpace.value(),responseContext.getEntity().toString());
        if(QyerUtils.isNotEmpty(response)){
            responseContext.setEntity(response);
        }
    }
}
